package public

import (
	"MoSkeleton/framework"
	"MoSkeleton/framework/core/consts"
	"MoSkeleton/framework/core/dto/request"
	"MoSkeleton/framework/core/moerrors"
	"MoSkeleton/framework/utils"
	"MoSkeleton/models/system"
	"MoSkeleton/services/base"
	system2 "MoSkeleton/services/system"
	"MoSkeleton/web/pogos/request/public"
	system3 "MoSkeleton/web/pogos/respose/system"
	"errors"
)

type AuthService struct {
	base.BaseService
}

func (a *AuthService) Login(req public.LoginReq, onlineUser *system3.OnlineUserResp) (string, error) {
	sysUser := system.SysUser{}
	ok, err := sysUser.GetWithPasswordByUsername(req.Username)
	if err != nil {
		return "", err
	} else if !ok {
		msg, _ := framework.Translater.Translate(consts.TKey_ErrorUsernameOrPasswdFail)
		return "", moerrors.NewValidateError(consts.CommLoginFailCode, msg)
	}
	ok = utils.PasswordValidateFromFront(req.Password, sysUser.Password, sysUser.Salt)
	if ok {
		claims := utils.NewJWT(&base.CommonGin.AuthGroup.Bearer).CreateClaims(request.BaseClaims{
			ID:       sysUser.ID,
			Username: sysUser.UserName,
			NickName: sysUser.NickName,
		}, &base.CommonGin.AuthGroup.Bearer)

		token, err := utils.NewJWT(&base.CommonGin.AuthGroup.Bearer).CreateToken(claims)
		if err != nil {
			return "", err
		}
		onlineUser.Token = token
		_, err = system2.SystemGroupInst.SysUserServiceInst.MakeUserOnline(sysUser.ID, onlineUser, claims.ExpiresAt)
		if err != nil {
			return "", err
		}
		return token, nil
	}
	errMsg, _ := framework.Translater.Translate(consts.TKey_ErrorUsernameOrPasswdFail)
	return "", errors.New(errMsg)
}
